package com.cloud.observer;


import com.cloud.observer.annotation.ScheduledObserver;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * @author: create by God of SJF
 * @version: v1.0
 * @description: com.cloud.observer
 * @date:2021/1/12
 */
@Aspect
public class ScheduledObserverAspect {

    @Autowired
    BaseScheduledObserver baseScheduledObserver;

    @Autowired
    ScheduledObserverWrapper scheduledObserverWrapper;

    @Autowired
    ScheduledObserverRefresher scheduledObserverRefresher;

    @Autowired
    ScheduledExceptionHandler scheduledExceptionHandler;


    @Pointcut(value = "@annotation(org.springframework.scheduling.annotation.Scheduled)")
    public void cut() {
    }

    @Before("cut() && @annotation(ScheduledObserver) && @annotation(Scheduled)")
    public void before(JoinPoint joinPoint, ScheduledObserver ScheduledObserver, Scheduled Scheduled) throws Exception {
        scheduledObserverRefresher.initOrRefresh(key(joinPoint), ScheduledObserver, Scheduled, null, 1);
    }

    @AfterReturning(returning = "re", pointcut = "cut() && @annotation(ScheduledObserver) && @annotation(Scheduled)")
    public void after(JoinPoint joinPoint, ScheduledObserver ScheduledObserver, Scheduled Scheduled, Object re) throws Exception {
        scheduledObserverRefresher.initOrRefresh(key(joinPoint), ScheduledObserver, Scheduled, re, 2);
    }

    @AfterThrowing(throwing = "ex", pointcut = "@annotation(ScheduledObserver)")
    public void throwCut(JoinPoint joinPoint, ScheduledObserver ScheduledObserver, Exception ex) {
        scheduledExceptionHandler.error(key(joinPoint), ex);
    }

    public String key(JoinPoint joinPoint) {
        String className = joinPoint.getSignature().getDeclaringTypeName();
        String methodName = joinPoint.getSignature().getName();
        String key = className.substring(className.lastIndexOf(".") + 1, className.length()) + "-" + methodName;
        return key;
    }
}
